package com.incom.log.server.monitor.telnet;

import com.incom.log.server.conf.ServiceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.Socket;

public class HandlerThread extends Thread {

    private static Logger log = LoggerFactory.getLogger(HandlerThread.class);

    private Socket client;

    public HandlerThread(Socket client) {
        this.client = client;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = client.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String len = null;
            while((len = reader.readLine()) != null && ServiceConfig.serverRunSts) {
                log.info("telnet client input : " + len);
                len = len.trim();
                if(len.startsWith("stop ")) {
                    String password = new TelnetConfig().getPassword();
                    if(password == null) {
                        log.info("log service shutdown ...");
                        try {
                            new TelnetServer().stopMonitor();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        continue;
                    }
                    if(len.equalsIgnoreCase("stop " + password)) {
                        log.info("log service shutdown ...");
                        try {
                            new TelnetServer().stopMonitor();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        continue;
                    }
                    log.error("password error ... ");
                }
            }
            OutputStream outputStream = client.getOutputStream();
            outputStream.write("shutdown success".getBytes());
            outputStream.flush();
            outputStream.close();
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
